package com.substation.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.greenentity.Eqpt;
import com.greenentity.Unit;
import com.interfaces.ResponseListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;
import com.substation.R;
import com.substation.greendao.EqptDao;
import com.substation.ui.dialog.CalendarDialog;
import com.substation.ui.utils.RecyclerViewUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by admin on 2017/12/25.
 */

public class DialogUtils {

    public static void showMsgDialog(Context c, String title, String msg, final DialogInterface.OnClickListener listener) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(c, R.style.dialogStyle);
        normalDialog.setTitle(title);
        normalDialog.setMessage(msg);
        normalDialog.setPositiveButton("确定", listener);
        normalDialog.setNegativeButton("关闭", null);
        normalDialog.show();
    }

    public static void showMsgDialog(Context c, String title, String msg) {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(c, R.style.dialogStyle);
        normalDialog.setTitle(title);
        normalDialog.setMessage(msg);
        normalDialog.setPositiveButton("确定", null);
        normalDialog.show();
    }

    public static void showMsgDialog(Context c, String title, String msg, String positiveMsg, String negativeMsg, final DialogInterface.OnClickListener positiveListener, final DialogInterface.OnClickListener negativeListener) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(c, R.style.dialogStyle);
        normalDialog.setTitle(title);
        normalDialog.setMessage(msg);
        normalDialog.setPositiveButton(positiveMsg, positiveListener);
        normalDialog.setNegativeButton(negativeMsg, negativeListener);
        normalDialog.show();
    }

    public static void showEditTextDialog(final Context c, String title, final ResponseListener<String> responseListener) {
        /*@setView 装入一个EditView*/
        final EditText editText = new EditText(c);
        editText.setTextColor(c.getResources().getColor(R.color.text_color_1));
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(c, R.style.dialogStyle);
        inputDialog.setTitle(title).setView(editText);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        KeyBoardUtils.closeKeybord(editText, c);
                        responseListener.response(editText.getText().toString());
                    }
                }).show();
    }

    public static void showEditTextInspectionDialog(final Context c, String title, final ResponseListener<String> responseListener) {
        /*@setView 装入一个EditView*/
        final EditText editText = new EditText(c);
        editText.setTextColor(c.getResources().getColor(R.color.text_color_1));
        editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        String digits_ = ".0123456789/";
        editText.setKeyListener(DigitsKeyListener.getInstance(digits_));
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(c, R.style.dialogStyle);
        inputDialog.setTitle(title).setView(editText);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        KeyBoardUtils.closeKeybord(editText, c);
                        responseListener.response(editText.getText().toString());
                    }
                }).show();
    }

    public static void showListEditTextDialog(final Activity c, String title, final String r, final List<String> content, final ResponseListener<String> responseListener) {
        final List<String> list = new ArrayList<>();
        final List<String> j = new ArrayList<>();
        for (String s : content) {
            list.add(s + "：");
            j.add(s + "：");
        }
        final Dialog dialog = new Dialog(c, R.style.dialogStyle);
        final View view = LayoutInflater.from(c).inflate(R.layout.dialog_list_edit, null);
        ((TextView) view.findViewById(R.id.title)).setText(title);
        view.findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String result = "";
                for (String s : j) {
                    if (!s.endsWith("：")) {
                        result += s + "；";
                    }
                }
                responseListener.response(result);
                dialog.cancel();
            }
        });
        final RecyclerView recyclerView = view.findViewById(R.id.list);
        recyclerView.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(c));
        recyclerView.addItemDecoration(new DividerItemDecoration(c, DividerItemDecoration.VERTICAL));
        SuperAdapter<String> adapter = new SuperAdapter<String>(R.layout.content_dialog_edit) {
            @Override
            public void bindView(ViewHolder viewHolder, final String s, final int i) {
                ((TextView) viewHolder.getView(R.id.header)).setText(s);
                final EditText editText = viewHolder.getView(R.id.edit);
                if (editText.getTag() instanceof TextWatcher) {
                    editText.removeTextChangedListener((TextWatcher) editText.getTag());
                }
                String[] p = new String[]{};
                if (!TextUtils.isEmpty(r)) {
                    p = r.split("；");
                }
                for (String s1 : p) {
                    if (s1.contains("：")) {
                        String[] p2 = s1.split("：");
                        if (p2.length > 1 && (p2[0] + "：").equals(s)) {
                            editText.setText(p2[1]);
                            String p3 = s + p2[1];
                            j.remove(i);
                            j.add(i, p3);
                        }
                    }
                }
                TextWatcher textWatcher = new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        String c = s + editable.toString();
                        j.remove(i);
                        j.add(i, c);
                    }
                };
                editText.addTextChangedListener(textWatcher);
                editText.setTag(textWatcher);
            }
        };
        recyclerView.setAdapter(adapter);
        adapter.setData(list);
        dialog.setTitle(title);
        dialog.setContentView(view);
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialogInterface) {
                int height = recyclerView.computeVerticalScrollRange();
                LinearLayout.LayoutParams layoutParams;
                if (height > ScreenUtils.getScreenHeight(c) / 3 * 2) {
                    layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ScreenUtils.getScreenHeight(c) / 3 * 2);
                } else {
                    layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, height);
                }
                recyclerView.setLayoutParams(layoutParams);
            }
        });
        dialog.show();
    }

    public static void showEditTextDialog(final Context c, String title, final ResponseListener<String> responseListener, String content) {
        /*@setView 装入一个EditView*/
        final EditText editText = new EditText(c);
        editText.setTextColor(c.getResources().getColor(R.color.text_color_1));
        editText.setText(content);
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(c, R.style.dialogStyle);
        inputDialog.setTitle(title).setView(editText);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        KeyBoardUtils.closeKeybord(editText, c);
                        responseListener.response(editText.getText().toString());
                    }
                }).show();
    }

    static int yourChoice = 0;

    public static void showEditTextDialog(final Context c, String title, final ResponseListener<String> responseListener, int InputType) {
        /*@setView 装入一个EditView*/
        final EditText editText = new EditText(c);
        editText.setTextColor(c.getResources().getColor(R.color.text_color_1));
        editText.setInputType(InputType);
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(c, R.style.dialogStyle);
        inputDialog.setTitle(title).setView(editText);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        KeyBoardUtils.closeKeybord(editText, c);
                        responseListener.response(editText.getText().toString());
                    }
                }).show();
    }

    public static void showChoiseDialog(Context c, String title, String[] items, final ResponseListener<Integer> responseListener) {
        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(c, R.style.dialogStyle);
        singleChoiceDialog.setTitle(title);
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        yourChoice = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        responseListener.response(yourChoice);
                        yourChoice = 0;
                    }
                });
        singleChoiceDialog.show();
    }

    static AlertDialog dialog = null;

    public static void showPhoneDialog(final Context c, final String phone, final String tel) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(c, R.style.dialogStyle);
        View view = LayoutInflater.from(c).inflate(R.layout.dialog_call, null);
        ((TextView) view.findViewById(R.id.phone)).setText("手机:" + phone);
        ((TextView) view.findViewById(R.id.tel)).setText("座机:" + tel);
        view.findViewById(R.id.phone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                call(c, phone);
                if (dialog != null) dialog.cancel();
            }
        });
        view.findViewById(R.id.tel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                call(c, tel);
                if (dialog != null) dialog.cancel();
            }
        });
        normalDialog.setTitle("拨打电话").setView(view);
        normalDialog.setNegativeButton("取消", null);
        dialog = normalDialog.show();
    }

    private static void call(Context c, String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        c.startActivity(intent);
    }

    public static void showEqpt(final Context c, Unit unit, final ResponseListener<Eqpt> listener) {
        List<Eqpt> eqpts = GreenDaoManager.getInstance().getmDaoSession().getEqptDao().queryBuilder().where(EqptDao.Properties.EqptGuid.eq(unit.getEqptGuid())).list();
        if (eqpts.size() > 0) {
            String unitName = eqpts.get(0).getUnitName();
            final AlertDialog.Builder normalDialog =
                    new AlertDialog.Builder(c, R.style.dialogStyle);
            final View view = LayoutInflater.from(c).inflate(R.layout.dialog_eqpt, null);
            RecyclerView recyclerView = view.findViewById(R.id.list);
            recyclerView.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(c));
            List<Eqpt> list = GreenDaoManager.getInstance().getNewSession().getEqptDao().queryBuilder().where(EqptDao.Properties.UnitName.eq(unitName)).list();
            SuperAdapter<Eqpt> adapter;
            recyclerView.setAdapter(adapter = new SuperAdapter<Eqpt>(R.layout.content_patro_content) {
                @Override
                public void bindView(ViewHolder viewHolder, final Eqpt eqpt, int i) {
                    ((TextView) viewHolder.getView(R.id.name)).setText(eqpt.getEqptName());
                    viewHolder.getView(R.id.layout).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            listener.response(eqpt);
                            if (dialog != null) dialog.cancel();
                        }
                    });
                }
            });
            adapter.setData(list);
            normalDialog.setTitle("选择所属设备").setView(view);
            normalDialog.setNegativeButton("取消", null);
            dialog = normalDialog.show();
        } else {
            showMsgDialog(c, "提示", "未找到该单元下属设备");
        }
    }

    public static void showCalendarDialog(FragmentManager fragmentManager, String title, ResponseListener<String> responseListener) {
        CalendarDialog calendarDialog = new CalendarDialog();
        calendarDialog.setInitDateAndListner("", title, responseListener);
        calendarDialog.show(fragmentManager, "");
    }

}
